from app import db, constants
from app.modules.user import user_blu
from flask import render_template, request, jsonify, session, redirect, abort
from app.utils.common import user_login_check
from flask import g, current_app
from app.utils.image_storage import storage
from app.models import Category, News, User
from app.utils.response_code import RET

# 其他用户信息页新闻列表
@user_blu.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)

# 其他用户信息页
@user_blu.route('/other_info')
@user_login_check
def other_info():
    """查看其他用户信息"""
    user = g.user

        
    # 获取其他用户id
    user_id = request.args.get("id")
    if not user_id:
        abort(404)
    # 查询用户模型
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 组织数据，并返回
    if user:
        data = {
            "user_info": user.to_dict(),
            "other_info": other.to_dict(),
            "is_followed": is_followed
        }
    else:
        data = {
            # "user_info": user.to_dict(),
            "other_info": other.to_dict(),
            "is_followed": is_followed
        }
    return render_template('news/other.html', data=data)


# 关注功能
@user_blu.route('/user_follow')
@user_login_check
def user_follow():
    current_page = request.args.get("p", 1)
    try:
        current_page = int(current_page)
    except Exception as e:
        current_app.logger.error(e)
        current_page = 1

    user = g.user
    totalPage = 1
    currentPage = 1
    user_followers = []

    try:
        paginate = user.followed.paginate(current_page, constants.USER_FOLLOWED_MAX_COUNT, False)
    except Exception as e:
        current_app.logger.error(e)

    totalPage = paginate.pages
    currentPage = paginate.page
    user_followers = [i.to_dict() for i in paginate.items]

    return render_template("news/user_follow.html",
                           data={
                               "totalPage": totalPage,
                               "currentPage": currentPage,
                               "user_followers": user_followers
                           })


# 新闻列表
@user_blu.route('/news_list')
@user_login_check
def news_list():
    current_page = request.args.get("p", 1)
    try:
        current_page = int(current_page)
    except Exception as e:
        current_app.logger.error(e)
        current_page = 1

    user = g.user
    totalPage = 1
    currentPage = 1
    news_list = []

    try:
        paginate = user.news_list.paginate(current_page, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)

    totalPage = paginate.pages
    currentPage = paginate.page
    news_list = [i.to_review_dict() for i in paginate.items]

    return render_template("news/user_news_list.html",
                           data={
                               "totalPage": totalPage,
                               "currentPage": currentPage,
                               "news_list": news_list
                           })


# 发布新闻
@user_blu.route('/release', methods=['GET', 'POST'])
@user_login_check
def release():
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

        categories_dic = [i.to_dict() for i in categories[1:]]

        return render_template("news/user_news_release.html",
                               categories_dic=categories_dic, data={})

    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    category_id = request.form.get("category_id")
    index_image = request.files.get("index_image")

    if not all([title, source, digest, content, category_id, index_image]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    try:
        index_image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数出错")

    try:
        image_url = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传七牛云出错")

    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_url
    news.category_id = category_id
    news.user_id = g.user.id

    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库存储出错")

    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


# 收藏功能
@user_blu.route('/collection')
@user_login_check
def collection():
    current_page = request.args.get("p", 1)
    try:
        current_page = int(current_page)
    except Exception as e:
        current_app.logger.error(e)
        current_page = 1

    user = g.user
    totalPage = 1
    currentPage = 1
    collections = []

    try:
        paginate = user.collection_news.paginate(current_page, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)

    totalPage = paginate.pages
    currentPage = paginate.page
    collections = [i.to_basic_dict() for i in paginate.items]

    return render_template("news/user_collection.html",
                           data={
                               "totalPage": totalPage,
                               "currentPage": currentPage,
                               "collections": collections
                           })


# 密码修改
@user_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_check
def pass_info():
    if request.method == 'GET':
        return render_template("news/user_pass_info.html",
                               data={
                                   "user_info": g.user.to_dict() if g.user else ''
                               })

    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if g.user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")

    g.user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库存储错误")

    return jsonify(errno=RET.OK, errmsg="密码修改成功")


# 头像更换
@user_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_check
def pic_info():
    if request.method == 'GET':
        return render_template("news/user_pic_info.html",
                               data={
                                   "user_info": g.user.to_dict() if g.user else '',
                                   "avatar_url": (constants.QINIU_DOMIN_PREFIX + g.user.avatar_url) if g.user.avatar_url else '../../static/news/images/user_pic.png'
                               })
    try:
        avatar_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="读取文件错误")

    try:
        image_url = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传七牛云出错")

    g.user.avatar_url = image_url
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库存储错误")
    return jsonify(errno=RET.OK, errmsg="头像更新成功", data={"avatar_url": constants.QINIU_DOMIN_PREFIX + image_url})


# 用户基本信息展示
@user_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_check
def base_info():
    if request.method == 'GET':
        return render_template("news/user_base_info.html",
                               data={
                                   "user_info": g.user.to_dict() if g.user else ''
                               })
    dict_data = request.json
    nick_name = dict_data.get("nick_name")
    signature = dict_data.get("signature")
    gender = dict_data.get("gender")

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="性别错误")

    g.user.nick_name = nick_name
    g.user.signature = signature
    g.user.gender = gender
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库存储错误")

    session["nick.name"] = nick_name

    return jsonify(errno=RET.OK, errmsg="基础信息更新成功")


@user_blu.route('/info')
@user_login_check
def user_info():
    # 判断用户是否登陆
    if not g.user:
        return redirect('/')

    # 拼接数据返回页面
    data = {
        "user_info": g.user.to_dict()
    }

    return render_template('news/user.html', data=data)
